<!--  -->
<template>
  <div class="container">
    <!-- <el-button type="text" @click="centerDialogVisible = true">点击打开 Dialog</el-button> -->
    <!-- <el-button type="text" @click="play">play</el-button>
    <el-button type="text" @click="pause">pause</el-button> -->
    <p class="title">离线床位</p>
    <div style="height:750px">
      <div class="contentBox">
        <div class="bedList" v-for="(item,index) in bedList" :key="index">
          <svg-icon icon-class="bed" class="icon" />
          <div style="padding-top:6px">{{ item.bedName }}</div>
        </div>
      </div>
    </div>

    <el-dialog title="报警提示" :visible.sync="centerDialogVisible" :close-on-click-modal= false :show-close= false width="65%" center>
      <div class="alarmBox">
        <div class="alarmList" v-for="(item , index) in alarmList" :key="index">
          <!-- <div class="box_1 textStyle">床位ID:{{ item.bedId }}</div> -->
          <div class="box_2 textStyle">{{ item.content }}</div>
          <div class="box_3 textStyle">发起人:{{ item.elderName }}</div>
          <!-- <div class="box_3 textStyle">发起方式:{{ item.helpMethod }}</div> -->
          <div class="box_3 textStyle">发起方式:按钮求助</div>
          <div class="box_4 textStyle">报警位置:{{ item.location }}</div>
          <!-- {{ item.taskType }} -->
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="popout">取 消</el-button>
        <el-button type="primary" @click="popout">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      class="controlBox"
      style="margin-top:20px"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[30,40,60,80]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
import { getOffLineBeds } from "@/api/user";
import Cookies from 'js-cookie'
import { mapGetters } from 'vuex'

const synth = window.speechSynthesis;
const msg = new SpeechSynthesisUtterance();

export default {
  name: 'Dashboard',
  components: {
     ...mapGetters([
      'name'
    ])
  },
  data() {
    return {
      id:'',
      regionId:'',
      centerDialogVisible: false,
      currentPage: 1, //  初始页
      pagesize: 30, //  每页的数据
      total: 0, //总条数

      websock: null, //建立的连接
      lockReconnect: false, //是否真正建立连接
      timeout: 20 * 1000, //一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时

      timeOutGetList: null, //定时获取列表
      bedList: [],
      alarmData: "", //报警信息
      loopPlay:'loop',  //循环播放
      loopPlayTimeOut:null, //循环播放计时器
      alarmList: [], //报警列表
    };
  },
  methods: {
    //初始获取一次
    getOffLineBedsFun() {
      var _this = this;
      getOffLineBeds(_this.currentPage, _this.pagesize,_this.regionId).then((res) => {
        this.setTimeFun();
        if (res.code == 2000) {
          _this.bedList = res.data.offLineBeds;
          _this.total = res.data.total;
        }
      });
    },
    //定时获取房间列表
    setTimeFun() {
      var _this = this;
      this.timeOutGetList = setInterval(function () {
        getOffLineBeds(_this.currentPage, _this.pagesize,_this.regionId).then((res) => {
          if (res.code == 2000) {
            _this.bedList = res.data.offLineBeds;
            _this.total = res.data.total;
          }
        });
      }, 15000);
    },

    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pagesize = size;
      this.getOffLineBedsFun();
      console.log(this.pagesize); //每页下拉显示数据
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
      this.getOffLineBedsFun();
      console.log(this.currentPage); //点击第几页
    },

    initWebSocket() {
      //建立连接
      //初始化weosocket
      const wsuri = "ws://110.187.88.70:21606/webSocket";
      // const wsuri = "ws://110.187.88.70:21704/webSocket";
      //建立连接
      this.websock = new WebSocket(wsuri);
      //连接成功
      this.websock.onopen = this.websocketonopen;
      //连接错误
      this.websock.onerror = this.websocketonerror;
      //接收信息
      this.websock.onmessage = this.websocketonmessage;
      //连接关闭
      this.websock.onclose = this.websocketclose;
    },
    reconnect(e) {
      //重新连接
      var that = this;
      if (that.lockReconnect) {
        return;
      } else {
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        that.timeoutnum && clearTimeout(that.timeoutnum);
        that.timeoutnum = setTimeout(function () {
          //新连接
          that.initWebSocket();
          that.lockReconnect = false;
        }, 5000);
      }
    },
    reset() {
      //重置心跳
      var that = this;
      //清除时间
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      //重启心跳
      that.start();
    },
    start() {
      //开启心跳
      var self = this;
      // self.timeoutObj && clearTimeout(self.timeoutObj);
      // self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self.timeoutObj = setInterval(function () {
        
        // 这里发送一个心跳，后端收到后，返回一个心跳消息
        if (self.websock.readyState == 1) {
          console.log('链接中》》'+self.regionId)
          //如果连接正常
          self.websock.send('S'+self.regionId);
        } else {
          //否则重连
          self.reconnect("心跳");
        }
      }, 30000);
    },
    //连接成功
    websocketonopen() {
      this.websocketsend('S'+this.regionId);
      // this.websock.send('S32');
      // this.websocketsend("E1");
      //提示成功
      console.log("连接成功");
      //开启心跳
      this.start();
    },
    //连接失败
    websocketonerror(e) {
      console.log("WebSocket连接发生错误");
      //重连
      this.reconnect("连接失败");
    },
    websocketclose(e) {
      //连接关闭事件
      console.log("连接已关闭", e);
      //重连
      // this.reconnect("关闭时重连");
    },
    websocketonmessage(event) {
      //接收服务器推送的信息
      //打开弹框
      this.centerDialogVisible = true;
      //打印收到服务器的内容
      console.log("收到服务器信息", event.data);
      this.alarmData = JSON.parse(event.data).content;
      this.alarmList.push(this.alarmData)
      //播放报警信息的第一条
      this.myplay(this.alarmData)
      //收到服务器信息，心跳重置
      this.reset();
    },
    websocketsend(msg) {
      //向服务器发送信息
      this.websock.send(msg);
    },
    //报警弹出层 关闭
    popout(){
      this.centerDialogVisible = false;
      //清除报警列表
      this.alarmList = []
      //关闭老人报警提示
      this.pause()
    },
    //语音播报报警信息
    myplay(ttsText) {
      
      let data = ttsText;
      var ttsTexts = `报警提示,${data.elderName}老人发起求助`;
      // var ttsTexts = `报警提示老人在激活报警`;
      msg.text = ttsTexts
      msg.lang = 'zh-CN'
      msg.volume = '1'
      msg.rate = 1
      msg.pitch = 2
      //激活循环报警
      this.play()
    },
    play(){
      this.centerDialogVisible = true
      if(this.centerDialogVisible == true){
        synth.speak(msg)
        this.loopPlayTimeOut = setInterval(() => {
          synth.speak(msg)
        }, 5000 );
      }
    },
    pause(){
      synth.cancel(msg)
      clearInterval(this.loopPlayTimeOut);
    }
  },
  computed: {},
  watch: {},
  created() {
    //获取id
    this.id = Cookies.get('ID')
    this.regionId = Cookies.get('regionID')
    this.getOffLineBedsFun();
    // //页面刚进入时开启长连接
    this.initWebSocket();
  },
  mounted() {
    // this.myplay()
  },
  updated() {},
  destroyed() {
    console.log('销毁')
    clearInterval(this.timeOutGetList);
    //清除时间
    clearTimeout(this.timeoutObj);
    //页面销毁时关闭长连接
    clearTimeout(this.serverTimeoutObj);
    this.websocketclose();
  },
};
</script>
<style lang='scss' >
.container {
  padding: 20px;
  // height: 100%;
  .icon {
    width: 80px;
    height: 80px;
  }
  .title {
    color: rgb(29, 46, 39);
    font-size: 16px;
    font-weight: 600;
  }
  .contentBox {
    // height: 80%;
    max-height: 770px;
    // width: 100%;
    display: flex;
    // justify-content: space-between;
    flex-wrap: wrap;
    overflow: auto;
    .bedList {
      margin-top: 20px;
      border: 1px solid rgb(177, 220, 228);
      background: #adc;
      color: rgb(69, 79, 90);
      border-radius: 5px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-content: center;
      width: 8%;
      min-width: 98px;
      height: 100px;
      margin-left: 1%;
      padding: 8px 1%;
      text-align: center;
    }
  }
  .alarmBox {
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    max-height: 400px;
    overflow: auto;
    .alarmList {
      margin: 5px;
      width: 18%;
      border: 1px dashed rgb(135, 184, 169);
      border-radius: 5px;
      padding: 8px;
      .textStyle {
        color: rgb(3, 53, 146);
      }
      .box_1 {
        font-size: 12px;
      }
      .box_2 {
        font-size: 16px;
        padding: 14px 0;
        text-align: center;
      }
    }
  }
  //   .controlBox{
  //       position: fixed;
  //       bottom: 70px;
  //   }
}
</style>